package com.butterfly.domain.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.butterfly.domain.entity.BaseEntity;

public abstract class AbstractDaoHibernate<E extends BaseEntity> implements GenericDAO<E> { 
	private SessionFactory sessionFactory;

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected abstract Class<E> getEntityClass();
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}	
	
	@Override
	public void save(E entity) {
		getSession().save(entity);
	}
	
	@Override
	public void update(E entity) {
		getSession().update(entity);
	}
	
	@Override
	public void delete(E entity) {
		getSession().delete(entity);
	}
	 
	@Override
	public void saveOrUpdate(E entity) {
		getSession().saveOrUpdate(entity);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public E findById(long id) {
		return (E) getSession().get(getEntityClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<E> getAll() {
		return getSession().createCriteria(getEntityClass()).list();
	}
	
	@Override
	public void evict(E entity) {
		getSession().evict(entity);
	}
	
	@Override
	public void refresh(E entity) {
		getSession().refresh(entity);
	}
	
	
}
